const fs = require('fs')

const vueRe = /(\w+)\.vue$/

async function createRoutes(path = './src/views') {
  const routes = []
  const dir = await fs.promises.opendir(path)
  for await(const dirent of dir) {
    const res = vueRe.exec(dirent.name)
    if (!res) {
      continue
    }
    const name = res[1]
    routes.push({
      path: `/${name}`,
      name
    })
  }
  writeRoutes(routes)
}

function createComponent(name) {
  const code = `aa() => import('../views/${name}.vue')aa`
  return code
}

function writeRoutes(routes) {
  routes.forEach(route => {
    const component = createComponent(route.name)
    route.component = component
  })
  const code = `
    const routes = ${JSON.stringify(routes)};
    export default routes;
  `;
  const re = /(")*aa(")*/g
  fs.writeFile('./src/router/routes.js', code.replace(re, () => ''), (err, written, string) => {
    console.log(err, written, string)
  })
}

createRoutes()